package com.baseweb.webadmin.controller.admin;

import com.baidu.ueditor.ActionEnter;
import com.baseweb.webadmin.alipay.util.AlipayNotify;
import com.baseweb.webadmin.alipay.util.AlipayParams;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.*;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.extshiro.ZheUsernamePasswordToken;
import com.baseweb.webadmin.extshiro.factoryBean.AdShiroFilterFactoryBean;
import com.baseweb.webadmin.service.*;
import com.baseweb.webadmin.core.util.CommonUtil;
import com.baseweb.webadmin.core.util.ConfigUtil;
import com.baseweb.webadmin.weixin.utils.HttpGetOrPost;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.codehaus.jackson.map.ObjectMapper;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class LoginController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    private final static String SESSION_CHECK_CODE = "checkCode";

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleRescService roleRescService;

    @Autowired
    private AdShiroFilterFactoryBean shiroFilter;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserOrderService userOrderService;

//    @RequestMapping(value = "/", method = RequestMethod.GET)
//    public String root(@RequestParam(value = "is_login", required = false) boolean is_login,
//                       @RequestParam(value = "current_city", required = false) String current_city,
//                       HttpServletRequest request,
//                       HttpServletResponse response,
//                       Model model) {
//        //        String userName = getUserName();
////        User user = userService.selectByName(getUserName());
////        model.addAttribute("misName", misName);
////        if (userName == null || userName.isEmpty()) {
////            return "redirect:/login";
////        }
////        model.addAttribute("username", userName);
//
////        String userName = getUserName();
////        if (StringUtils.isNotBlank(userName)){
////            User user = userService.selectByName(getUserName());
////            model.addAttribute("username", userName);
////            model.addAttribute("user", user);
////
//////            HttpSession session = request.getSession();
////
//////            session.removeAttribute("username");
//////            session.setAttribute("username", userName);
////        }
////
////
////        //分类
////        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
////        model.addAttribute("topList", topList);
////
////        //顶部轮播
////        List<ByAd> adList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 10);
////        model.addAttribute("adList", adList);
////
////        List<ByAd> centerLunboList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 5);
////        model.addAttribute("centerLunboList", centerLunboList);
////
////        List<ByAd> centerBottomList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_BOTTOM.getCode(), BaseState.NORMAL.getCode(), 0, 3);
////        model.addAttribute("centerBottomList", centerBottomList);
////
////        List<ByAd> centerRightList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_RIGHT.getCode(), BaseState.NORMAL.getCode(), 0, 2);
////        model.addAttribute("centerRightList", centerRightList);
////
////        List<ByAd> curList = contentService.selectAdListByPage(AdPositionType.CURRENT_RECOMMEND.getCode(), 0, BaseState.NORMAL.getCode(), 0, 8);
////        model.addAttribute("curList", curList);
////
////        List<ByAd> classicList = contentService.selectAdListByPage(AdPositionType.CLASSIC_EXAMPLE.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("classicOne", classicList.get(0));
////        model.addAttribute("classicList", classicList.subList(1, classicList.size()));
////
////        List<ByChannel> leftList = contentService.selectChannelListByPage(ChannelType.LEFT_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 10);
////        model.addAttribute("leftList", leftList);
////
////        List<ByNotice> noticeList = contentService.selectNoticeListByPage(null, null,0, 20);
////        model.addAttribute("noticeList", noticeList);
////
////        //策划师
////        List<ByAd> cehuaList = contentService.selectAdListByPage(AdPositionType.INDEX_CEHUA.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("cehuaOne", cehuaList.get(0));
////        model.addAttribute("cehuaList", cehuaList.subList(1, cehuaList.size()));
////
////        //主持
////        List<ByAd> zhuchiList = contentService.selectAdListByPage(AdPositionType.INDEX_ZHUCHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("zhuchiOne", zhuchiList.get(0));
////        model.addAttribute("zhuchiList", zhuchiList.subList(1, zhuchiList.size()));
////
////        //摄影师
////        List<ByAd> sysList = contentService.selectAdListByPage(AdPositionType.INDEX_SHEYINGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("sysOne", sysList.get(0));
////        model.addAttribute("sysList", sysList.subList(1, sysList.size()));
////
////        //化妆师
////        List<ByAd> hzsList = contentService.selectAdListByPage(AdPositionType.INDEX_HUAZHUANGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("hzsOne", hzsList.get(0));
////        model.addAttribute("hzsList", hzsList.subList(1, hzsList.size()));
////
////        //摄像师
////        List<ByAd> sxsList = contentService.selectAdListByPage(AdPositionType.INDEX_SHEXIANGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
////        model.addAttribute("sxsOne", sxsList.get(0));
////        model.addAttribute("sxsList", sxsList.subList(1, sxsList.size()));
////
////
////        Map<String, List<ByChannel>> map = new HashMap<String, List<ByChannel>>();
////        for (ByChannel byChannel: leftList) {
////            List<ByChannel> leftSubList = contentService.selectChannelListByPage(ChannelType.LEFT_CHANNEL.getCode(), byChannel.getId(), BaseState.NORMAL.getCode(), 0, 10);
////
////            map.put(byChannel.getId().toString(), leftSubList);
////        }
////        model.addAttribute("leftSubMap", map);
////
////        //tag list
////        Map<String, List<ByChannelKeyword>> map_kw = new HashMap<String, List<ByChannelKeyword>>();
////        for (ByChannel byChannel: leftList) {
////            List<ByChannelKeyword> leftSubList = contentService.selectKeyWordListByPage(ChannelType.LEFT_CHANNEL.getCode(), byChannel.getId(), null, BaseState.NORMAL.getCode(), 0, Integer.MAX_VALUE);
////
////            map_kw.put(byChannel.getId().toString(), leftSubList);
////        }
////        model.addAttribute("leftSubKWMap", map_kw);
////
////
////        HttpSession session = request.getSession();
////
////        String address = "";
////        if (StringUtils.isBlank((String) session.getAttribute("current_city"))) {
////
////            String ip = request.getRemoteAddr();
////
////            try {
////                address = IPSeeker.getAddress("ip=" + ip, "utf-8");
////            } catch (Exception e) {
////                address = "成都市";
////                logger.info("获取IP地理位置失败", e.getMessage());
////            }
////        }else{
////            if (StringUtils.isNotBlank(current_city)){
////                address = current_city;
////            }else{
////                address = (String) session.getAttribute("current_city");
////            }
////        }
////
////        session.setAttribute("current_city", address);
////        session.setAttribute("city_list", userService.selectAllCitiesList());
////        List<String> areaList = new ArrayList<String>();
////        if (StringUtils.isNotBlank(address)) {
////            areaList = CitiesUtil.getAreasListByCityName(address);
////        }
////        session.setAttribute("area_list", areaList);
//
//        return "main.html";
//    }

    @RequestMapping(value = "/index")
    public String index(@RequestParam(value = "is_pc", required = false) boolean is_pc,
                        @RequestParam(value = "is_login", required = false) boolean is_login,
                        @ModelAttribute("message") String message,
//                        @RequestParam(value = "current_city", required = false) String current_city,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Model model) {

//          if (is_pc){
//            model.addAttribute("isPc", is_pc);
//          }
//
////        String userName = getUserName();
////        User user = userService.selectByName(getUserName());
////        model.addAttribute("misName", misName);
////        if (userName == null || userName.isEmpty()) {
////            return "redirect:/login";
////        }
////        model.addAttribute("username", userName);
//
////        int trolleyTotal = 0;
//
//        if (is_login){
//            model.addAttribute("result", "登录成功!");
//        }
//
//        if (StringUtils.isNotBlank(message)){
//            model.addAttribute("result", message);
//        }
//
//        String userName = getUserName();
//        if (StringUtils.isNotBlank(userName)){
//            User user = userService.selectByName(getUserName());
//
//            if (user != null && user.getStatus().intValue() == BaseState.NORMAL.getCode()) {
//                model.addAttribute("username", userName);
//                model.addAttribute("user", user);
//            }
//
////            HttpSession session = request.getSession();
////
////            session.removeAttribute("username");
////            session.setAttribute("username", userName);
//
////            trolleyTotal = userService.selectTrolleyListCount(user.getId());
//        }
////        model.addAttribute("trolleyTotal", trolleyTotal);
//
//        //分类
//        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
//        model.addAttribute("topList", topList);
//
//        //顶部轮播
//        List<ByAd> adList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 10);
//        model.addAttribute("adList", adList);
//
//        List<ByAd> centerLunboList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 5);
//        model.addAttribute("centerLunboList", centerLunboList);
//
//        List<ByAd> centerBottomList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_BOTTOM.getCode(), BaseState.NORMAL.getCode(), 0, 3);
//        model.addAttribute("centerBottomList", centerBottomList);
//
//        List<ByAd> centerRightList = contentService.selectAdListByPage(AdPositionType.INDEX_CENTER_RIGHT.getCode(), BaseState.NORMAL.getCode(), 0, 2);
//        model.addAttribute("centerRightList", centerRightList);
//
//        List<ByAd> curList = contentService.selectAdListByPage(AdPositionType.CURRENT_RECOMMEND.getCode(), 0, BaseState.NORMAL.getCode(), 0, 8);
//        model.addAttribute("curList", curList);
//
//        List<ByAd> classicList = contentService.selectAdListByPage(AdPositionType.CLASSIC_EXAMPLE.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("classicOne", classicList.get(0));
//        model.addAttribute("classicList", classicList.subList(1, classicList.size()));
//
//        List<ByChannel> leftList = contentService.selectChannelListByPage(ChannelType.LEFT_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 10);
//        model.addAttribute("leftList", leftList);
//
//        List<ByNotice> noticeList = contentService.selectNoticeListByPage(null, null,0, 20);
//        model.addAttribute("noticeList", noticeList);
//
//        //策划师
//        List<ByAd> cehuaList = contentService.selectAdListByPage(AdPositionType.INDEX_CEHUA.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("cehuaOne", cehuaList.get(0));
//        model.addAttribute("cehuaList", cehuaList.subList(1, cehuaList.size()));
//
//        //主持
//        List<ByAd> zhuchiList = contentService.selectAdListByPage(AdPositionType.INDEX_ZHUCHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("zhuchiOne", zhuchiList.get(0));
//        model.addAttribute("zhuchiList", zhuchiList.subList(1, zhuchiList.size()));
//
//        //摄影师
//        List<ByAd> sysList = contentService.selectAdListByPage(AdPositionType.INDEX_SHEYINGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("sysOne", sysList.get(0));
//        model.addAttribute("sysList", sysList.subList(1, sysList.size()));
//
//        //化妆师
//        List<ByAd> hzsList = contentService.selectAdListByPage(AdPositionType.INDEX_HUAZHUANGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("hzsOne", hzsList.get(0));
//        model.addAttribute("hzsList", hzsList.subList(1, hzsList.size()));
//
//        //摄像师
//        List<ByAd> sxsList = contentService.selectAdListByPage(AdPositionType.INDEX_SHEXIANGSHI.getCode(), 0, BaseState.NORMAL.getCode(), 0, 7);
//        model.addAttribute("sxsOne", sxsList.get(0));
//        model.addAttribute("sxsList", sxsList.subList(1, sxsList.size()));
//
//        Map<String, List<ByChannel>> map = new HashMap<String, List<ByChannel>>();
//        for (ByChannel byChannel: leftList) {
//            List<ByChannel> leftSubList = contentService.selectChannelListByPage(ChannelType.LEFT_CHANNEL.getCode(), byChannel.getId(), BaseState.NORMAL.getCode(), 0, 10);
//
//            map.put(byChannel.getId().toString(), leftSubList);
//        }
//        model.addAttribute("leftSubMap", map);
//
//        //tag list
//        Map<String, List<ByChannelKeyword>> map_kw = new HashMap<String, List<ByChannelKeyword>>();
//        for (ByChannel byChannel: leftList) {
//            List<ByChannelKeyword> leftSubList = contentService.selectKeyWordListByPage(ChannelType.LEFT_CHANNEL.getCode(), byChannel.getId(), null, BaseState.NORMAL.getCode(), 0, Integer.MAX_VALUE);
//
//            map_kw.put(byChannel.getId().toString(), leftSubList);
//        }
//        model.addAttribute("leftSubKWMap", map_kw);
//
//
//
//        HttpSession session = request.getSession();
//
//        String address = "";
//        if (StringUtils.isBlank((String) session.getAttribute("current_city"))) {
//
//            String ip = request.getRemoteAddr();
//
//            try {
//                address = IPSeeker.getAddress("ip=" + ip, "utf-8");
//            } catch (Exception e) {
//                address = "成都市";
//                logger.info("获取IP地理位置失败", e.getMessage());
//            }
//        }else{
////            if (StringUtils.isNotBlank(current_city)){
////                address = current_city;
////            }else{
////                address = (String) session.getAttribute("current_city");
////            }
//            address = (String) session.getAttribute("current_city");
//        }
//
//        session.setAttribute("current_city", address);
//        session.setAttribute("city_list", userService.selectAllCitiesList());
//
//        List<String> areaList = new ArrayList<String>();
//        if (StringUtils.isNotBlank(address)) {
//            areaList = CitiesUtil.getAreasListByCityName(address);
//        }
//        session.setAttribute("area_list", areaList);
        return "system_main.html";
    }

    @RequestMapping(value = "/ad_list", method = RequestMethod.GET)
    public String ad_list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize,
                          @RequestParam(value = "parent_id", required = true) Integer parent_id,
                          @RequestParam(value = "position_id", required = true) Integer position_id,
                          Model model) {

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        model.addAttribute("positionName", AdPositionType.getNameByCode(position_id).getName());

        ByAd parent = contentService.findAd(parent_id);
        if (parent != null) {
            model.addAttribute("columnName", parent.getName());
        }

        if (position_id == AdPositionType.INDEX_CEHUA.getCode()
                || position_id == AdPositionType.INDEX_ZHUCHI.getCode()
                || position_id == AdPositionType.INDEX_SHEYINGSHI.getCode()
                || position_id == AdPositionType.INDEX_HUAZHUANGSHI.getCode()
                || position_id == AdPositionType.INDEX_SHEXIANGSHI.getCode() ){
            model.addAttribute("is_show", true);
        }

        int total = 0;
//        if (position_id.intValue() == 3 || position_id.intValue() == 4) {
            List<ByAd> list = contentService.selectAdListByPage(position_id, parent_id, BaseState.NORMAL.getCode(), (page - 1) * pageSize, pageSize);
            total = contentService.selectAdListCount(position_id, parent_id, BaseState.NORMAL.getCode());

            model.addAttribute("bizList", list);
//        }else{
//            List<UserInfoDetailBvo> list = new ArrayList<UserInfoDetailBvo>();
//
//            List<Integer> userIds = new ArrayList<Integer>();
//            List<ByAd> adList = contentService.selectAdListByPage(position_id, parent_id, (page - 1) * pageSize, pageSize);
//
//            if (adList != null && adList.size() > 0){
//                for (ByAd current : adList){
//                    userIds.add(current.getEntityId());
//                }
//            }
//
//            List<User> bizList = userService.selectUserByIds(userIds);
//
//            if (bizList != null && bizList.size() > 0){
//                for (User current : bizList){
//                    List<ByUserBizProduct> productList = userService.selectProductListByPage(current.getId(), null, null,0, 4,
//                            null, null, null, null, BaseState.NORMAL.getCode());
//                    List<ByUserBizAuth> authList = userService.selectBizVerifyListByPage(current.getId(), null, null,0, 4, BaseState.NORMAL.getCode());
//                    UserInfoDetailBvo bvo = UserInfoDetailBvo.copyFrom(current, productList, authList, contentService.findChannel(current.getBizWorkType()));
//
//                    list.add(bvo);
//                }
//            }
//
//            model.addAttribute("bizList", list);
//
//        }
        model.addAttribute("total", total);

        int totalPage = total/pageSize;
        int tmpDiv = total%pageSize;
        if (tmpDiv > 0){
            totalPage +=1;
        }
        model.addAttribute("totalPage", totalPage);

        model.addAttribute("currentPage", page);

        model.addAttribute("pageSize", pageSize);

        model.addAttribute("parent_id", parent_id);

        model.addAttribute("position_id", position_id);

        return "ad_list";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);
        return "register";
    }

    @RequestMapping(value = "/biz_register", method = RequestMethod.GET)
    public String biz_register(Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);
        return "biz_register";
    }

    @RequestMapping(value = "/privacy", method = RequestMethod.GET)
    public String privacy(Model model) {
        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);
        return "privacy";
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public String download(Model model) {
        //顶部轮播
        List<ByAd> adList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 10);
        model.addAttribute("adList", adList);

        return "download";
    }

    @RequestMapping(value = "/play_video", method = RequestMethod.GET)
    public String play_video(@RequestParam(value = "example_id", required = false) Integer example_id,
                        Model model) {

        if (example_id != null && example_id > 0){
            ByUserExample example = userService.findExample(example_id);

            model.addAttribute("example", example);
        }

        return "play_video";
    }

    @RequestMapping(value = "/forgetPwd", method = RequestMethod.GET)
    public String forgetPwd(Model model) {
        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);
        return "forgetPwd";
    }

    @RequestMapping(value = "/change_city", method = RequestMethod.GET)
    public String change_city(HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam(value = "city", required = false) String city,
//                              RedirectAttributes redirectAttributes,
                              Model model) {
//        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);

        List<ByAd> adList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 10);
        model.addAttribute("adList", adList);

        String pathUrl = request.getHeader("referer");

//        redirectAttributes.addAttribute("current_city", city);

        HttpSession session = request.getSession();
        session.setAttribute("current_city", city);

        session.setAttribute("city_list", userService.selectAllCitiesList());

        List<String> areaList = new ArrayList<String>();
        if (StringUtils.isNotBlank(city)) {
            areaList = CitiesUtil.getAreasListByCityName(city);
        }
        session.setAttribute("area_list", areaList);

        if (pathUrl.indexOf("com") != -1){
            pathUrl = pathUrl.split("com")[1];
        }

        if (pathUrl.indexOf("8000") != -1){
            pathUrl = pathUrl.split("8000")[1];
        }

        return "redirect:"+pathUrl;
    }

    @RequestMapping(value = "/biz_example", method = RequestMethod.GET)
    public String biz_example(@RequestParam(value = "example_id", required = false) Integer example_id,
                        Model model) {

        List<Map<String, String>> imgList= new ArrayList<Map<String, String>>();

        List<ByUserExampleDetail> list = userService.selectExampleDetailListByPage(null, example_id, null, 0, Integer.MAX_VALUE);

        if (list != null && list.size() > 0){
            for (ByUserExampleDetail current : list){
                Map map = new HashMap();
                map.put("src", "http://img.boyitongcheng.com/"+current.getImgUrl());
                map.put("w","1024");
                map.put("h","800");
                map.put("title",current.getName());
                imgList.add(map);
            }
        }else{
            ByUserExample byUserExample = userService.findExample(example_id);
            Map map = new HashMap();
            map.put("src", "http://img.boyitongcheng.com/"+byUserExample.getImgUrl());
            map.put("w","1024");
            map.put("h","800");
            map.put("title",byUserExample.getName());
            imgList.add(map);
        }

        try {
            model.addAttribute("imgList", new ObjectMapper().writeValueAsString(imgList));
        } catch (IOException e) {
            model.addAttribute("imgList", "");
        }

        return "biz_example";
    }

    @RequestMapping(value = "/notice", method = RequestMethod.GET)
    public String notice(@RequestParam(value = "id", required = false) Integer id,
                         Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        List<ByNotice> noticeList = contentService.selectNoticeListByPage(null, null,0, 20);
        model.addAttribute("noticeList", noticeList);

        if (id !=null && id > 0){
            ByNotice byNotice = contentService.findNotice(id);
            model.addAttribute("notice", byNotice);

            if (byNotice != null){
                int viewCount = 1;
                if (byNotice.getViewCount() != null && byNotice.getViewCount() > 0){
                    viewCount = byNotice.getViewCount() + 1;
                }
                byNotice.setViewCount(viewCount);
                contentService.insertNotice(byNotice);
            }
        }else{
            return "accessDenied";
        }

        return "notice";
    }

    @RequestMapping(value = "/ad", method = RequestMethod.GET)
    public String ad(@RequestParam(value = "id", required = false) Integer id,
                     Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        List<ByAd> adList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), BaseState.NORMAL.getCode(), 0, 10);
        model.addAttribute("adList", adList);

        if (id !=null && id > 0){
            ByAd byAd = contentService.findAd(id);
            model.addAttribute("ad", byAd);
        }else{
            return "accessDenied";
        }

        return "ad";
    }

    @RequestMapping(value = "/article", method = RequestMethod.GET)
    public String article(@RequestParam(value = "id", required = false) Integer id,
                          Model model) {
        UserForm userForm = new UserForm();
        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        if (id !=null && id > 0){
            ByArticle byArticle = contentService.findArticle(id);
            model.addAttribute("article", byArticle);

            List<ByArticle> articleList = contentService.selectArticleListByPage(null, byArticle.getPositionId(), byArticle.getArticleType(),0, 20);
            model.addAttribute("articleList", articleList);

            byArticle.setViewCount(byArticle.getViewCount()+1);
            contentService.insertArticle(byArticle);
        }else{
            return "accessDenied";
        }

        return "article";
    }

    @RequestMapping(value = "/list")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                       @RequestParam(value = "user_id", required = false) Integer user_id,
                       @RequestParam(value = "product_type", required = false) Integer product_type,
                       @RequestParam(value = "parent_id", required = false) Integer parent_id,
                       @RequestParam(value = "channel_id", required = false) Integer channel_id,
                       @RequestParam(value = "position_id", required = false) Integer position_id,
                       @RequestParam(value = "sort", required = false) String sort,
                       @RequestParam(value = "style_type", required = false) String style_type,
                       @RequestParam(value = "price", required = false) String price,
                       @RequestParam(value = "keyword", required = false) String keyword,
                       @RequestParam(value = "city", required = false) String city,
                       @RequestParam(value = "area", required = false) String area,
                       HttpServletRequest request,
                       HttpServletResponse response,
                       Model model) {
        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);

        HttpSession session = request.getSession();

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        for (ByChannel current : topList){
            if (channel_id != null && channel_id.intValue() > 0 && current.getId().intValue() == channel_id.intValue()){
                model.addAttribute("channel", current);
            }
        }

        model.addAttribute("topList", topList);

//        List<ByUserBizProduct> productList = userService.selectProductListByPage(null, product_type, channel_id,(page-1)*pageSize, pageSize,
//                                                        sort, style_type, price, keyword);
//        int total = userService.selectProductListCount(null, product_type, channel_id,sort, style_type, price, keyword);

        if (StringUtils.isBlank(city)){
            city = (String) session.getAttribute("current_city");
            if (StringUtils.isBlank(city)){
                city = "成都市";
                session.setAttribute("current_city", city);
            }
        }

        List<UserInfoDetailBvo> list = new ArrayList<UserInfoDetailBvo>();
        List<User> bizList = userService.selectBizUserListByPage(product_type,null,channel_id,sort,style_type,price,keyword,(page-1)*pageSize, pageSize,
                BaseState.NORMAL.getCode(),city, area, null);
        int total = userService.selectBizUserListCount(product_type,null,channel_id,sort,style_type,price,keyword,
                BaseState.NORMAL.getCode(),city, area);


        if (bizList != null && bizList.size() > 0){
            for (User current : bizList){
                List<ByUserBizProduct> productList = userService.selectProductListByPage(current.getId(), null, null,0, 4,
                        null, null, null, null, BaseState.NORMAL.getCode());
                List<ByUserBizAuth> authList = userService.selectBizVerifyListByPage(current.getId(), null, null,0, 4, BaseState.NORMAL.getCode());
                UserInfoDetailBvo bvo = UserInfoDetailBvo.copyFrom(current, productList, authList, contentService.findChannel(current.getBizWorkType()));

                list.add(bvo);
            }
        }

        model.addAttribute("bizList", list);
        model.addAttribute("total", total);

        int totalPage = total/pageSize;
        int tmpDiv = total%pageSize;
        if (tmpDiv > 0){
            totalPage +=1;
        }
        model.addAttribute("totalPage", totalPage);

        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", pageSize);

        model.addAttribute("parent_id", parent_id);
        model.addAttribute("channel_id", channel_id);
        model.addAttribute("position_id", position_id);
        model.addAttribute("style_type", style_type);
        model.addAttribute("price", price);
        model.addAttribute("keyword", keyword);

//        String address = (String) session.getAttribute("current_city");
//
//        if (StringUtils.isBlank(address)){
//            address = "成都市";
//        }

        model.addAttribute("city", city);
        model.addAttribute("area", area);

        if (StringUtils.isNotBlank(city)) {
            session.setAttribute("area_list", CitiesUtil.getAreasListByCityName(city));
        }

        return "list";
    }

    @RequestMapping(value = "/biz_index")
    public String biz_index(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                       @RequestParam(value = "user_id", required = false) Integer user_id,
                       Model model) {
//        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);


        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

//        List<ByUserBizProduct> productList = userService.selectProductListByPage(null, product_type, channel_id,(page-1)*pageSize, pageSize,
//                sort, style_type, price, keyword);
//        int total = userService.selectProductListCount(null, product_type, channel_id,sort, style_type, price, keyword);
//
//        model.addAttribute("productList", productList);
//        model.addAttribute("total", total);
//        model.addAttribute("pageSize", pageSize);

        User user = userService.selectUserById(user_id);
        model.addAttribute("user", user);

        if (user.getBizViewCount() != null && user.getBizViewCount() > 0){
            user.setBizViewCount(user.getBizViewCount() + 1);
            userService.updateUser(user);
        }else{
            user.setBizViewCount(1);
            userService.updateUser(user);
        }

        User currentUser = getCurrentUser();

        if (currentUser != null && user != null && (currentUser.getId().intValue() == user.getId().intValue())) {
            model.addAttribute("is_me", "");
        }

        ByChannel channel = contentService.findChannel(user.getBizWorkType());
        model.addAttribute("channel", channel);

        List<ByUserBizAuth> authList = userService.selectBizVerifyListByPage(user.getId(), null, null, 0,5, BaseState.NORMAL.getCode());
        model.addAttribute("authList", authList);

        List<ByUserBizProduct> productList = userService.selectProductListByPage(user.getId(), null, null, 0, 20,null,null,null,null, BaseState.NORMAL.getCode());
        model.addAttribute("productList", productList);

        List<ByUserExample> exampleList = userService.selectExampleListByPage(user.getId(),BaseState.NORMAL.getCode(), null, 0, 8);
        model.addAttribute("exampleList", exampleList);


        //开通城市
        Map<String, List<String>> openCitiesMap = new HashMap<String, List<String>>();
        List<ByOpenCity> opencities = userService.selectAllCitiesObjectList(user.getId());
        if (opencities !=null && opencities.size() > 0){
            Set provinceSet = new HashSet();

            for (ByOpenCity current : opencities){
                if (!provinceSet.contains(current.getProvince())){
                    List<String> tmpCities = new ArrayList<String>();
                    openCitiesMap.put(current.getProvince(), tmpCities);
                    provinceSet.add(current.getProvince());
                }
            }
            model.addAttribute("openProvinces", new ArrayList<String>(provinceSet));

            Set citiesSet = new HashSet();
            for (ByOpenCity current : opencities){
                if (!citiesSet.contains(current.getCity())){
                    List<String> tmpCities = openCitiesMap.get(current.getProvince());
                    tmpCities.add(current.getCity());
                    citiesSet.add(current.getCity());
                }
            }
        }
        model.addAttribute("openCitiesMap", openCitiesMap);


        //评论
//        List<ByUserOrderDetail> detailList = userOrderService.selectOrderDetailListByPage(user_id, null, 0, Integer.MAX_VALUE);
//        List<OrderCommentBvo> detailBvoList = new ArrayList<OrderCommentBvo>();
//        if (detailList != null && detailList.size() > 0){
//            for (ByUserOrderDetail current : detailList){
//                OrderCommentBvo bvo = OrderCommentBvo.copyFrom(current, userService.selectUserById(current.getUserId()));
//                detailBvoList.add(bvo);
//            }
//        }

        List<ByUserOrder> commentList = userOrderService.selectOrderListByBizUser(null, user_id, OrderStatus.CONFIRM_ORDER.getCode(), null,0, Integer.MAX_VALUE);

        List<OrderCommentBvo> detailBvoList = new ArrayList<OrderCommentBvo>();
        if (commentList != null && commentList.size() > 0){
            for (ByUserOrder current : commentList){
                OrderCommentBvo bvo = OrderCommentBvo.copyFrom(current, userService.selectUserById(current.getUserId()));
                detailBvoList.add(bvo);
            }
        }
        model.addAttribute("commentList", detailBvoList);


        //档期
//        List<ByUserBizSchedule> scheduleList = userOrderService.selectScheduleListByPage(user_id,null,0,Integer.MAX_VALUE);
//        model.addAttribute("scheduleList",scheduleList);

        Map<String, String> scheduleData = userOrderService.getUserScheduleListView(user_id, 0, 0);

        if (scheduleData != null && scheduleData.keySet().size() > 0) {
            try {
                model.addAttribute("scheduleData", new ObjectMapper().writeValueAsString(scheduleData));

//                for (Iterator iter = scheduleData.keySet().iterator(); iter.hasNext();) {
//                    String tmpKey = (String) iter.next();
//
//                    if (scheduleData.get(tmpKey).equalsIgnoreCase("greyClass")){
//
//                    }
//                }
            } catch (IOException e) {
                model.addAttribute("scheduleData", "");
                e.printStackTrace();
            }
        }else{
            model.addAttribute("scheduleData", "");
        }

        //信誉
        String creditStr = CommonUtil.getBizCreditFlag(user.getBizDealCount());
        if (StringUtils.isNotBlank(creditStr)) {
            model.addAttribute("creditData", creditStr);
        }

        List<ByUserRecommendBvo> list = new ArrayList<ByUserRecommendBvo>();
        List<ByUserRecommend> byUserRecommends = userService.selectRecommendUserListByPage(user_id, null, null, 0, Integer.MAX_VALUE);

        if (byUserRecommends != null && byUserRecommends.size() > 0){
            for (ByUserRecommend current : byUserRecommends){
                User recommendUser = userService.selectUserById(current.getRecommendId());
                if (recommendUser != null) {
                    UserInfoBvo recommendUserBvo = UserInfoBvo.copyFrom(recommendUser, null, contentService.findChannel(recommendUser.getBizWorkType()));
                    list.add(ByUserRecommendBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
                            recommendUserBvo, userService.findExample(current.getExampleId())));
                }
            }
        }
        model.addAttribute("recommendUsers", list);

        return "biz_index";
    }

    @RequestMapping(value = "/biz_case")
    public String biz_case(@RequestParam(value = "example_id", required = false) Integer example_id,
                            Model model) {
        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        if (example_id != null && example_id > 0) {
            ByUserExample byUserExample = userService.findExample(example_id);

            List<ByUserExampleDetail> byUserExampleDetails = userService.selectExampleDetailListByPage(null, example_id, null, 0, Integer.MAX_VALUE);

            User user = userService.selectUserById(byUserExample.getUserId());
            UserInfoBvo userInfoBvo = UserInfoBvo.copyFrom(userService.selectUserById(byUserExample.getUserId()), null, contentService.findChannel(user.getBizWorkType()));

            List<ByUserRecommendBvo> list = new ArrayList<ByUserRecommendBvo>();
            List<ByUserRecommend> byUserRecommends = userService.selectRecommendUserListByPage(byUserExample.getUserId(), null, example_id, 0, Integer.MAX_VALUE);

            if (byUserRecommends != null && byUserRecommends.size() > 0){
                for (ByUserRecommend current : byUserRecommends){
                    User recommendUser = userService.selectUserById(current.getRecommendId());
                    UserInfoBvo recommendUserBvo = UserInfoBvo.copyFrom(recommendUser, null, contentService.findChannel(recommendUser.getBizWorkType()));
                    list.add(ByUserRecommendBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
                            recommendUserBvo, userService.findExample(current.getExampleId())));
                }
            }

            model.addAttribute("userInfoBvo", userInfoBvo);
            model.addAttribute("recommendUsers", list);

            model.addAttribute("example", byUserExample);
            model.addAttribute("exampleDetails", byUserExampleDetails);
        }

        return "biz_case";
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(Model model) {
        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
//        model.addAttribute("misName", misName);


        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        return "list";
    }

    @RequestMapping(value = "/welcome")
    public String welcome(Model model) {
        return "/common/welcome";
    }

    @RequestMapping(value = "/right", method = RequestMethod.GET)
    public String right(Model model) {
//        String userName = getUserName();
//        User user = userService.selectByName(getUserName());
//        model.addAttribute("misName", misName);
//        if (userName == null || userName.isEmpty()) {
//            return "redirect:/login";
//        }
//        model.addAttribute("username", userName);

        User user = getCurrentUser();
        model.addAttribute("user", user);

        List<ByUserBizAuth> verifies = userService.selectBizVerifyListByPage(user.getId(), null, null,0, 10, null);

        model.addAttribute("verifies", verifies);

        return "right";
    }

    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String manage(@RequestParam(value = "src", defaultValue = "right.ftl") String src,
                        Model model) {
        String userName = getUserName();
//        User user = userService.selectByName(getUserName());
//        model.addAttribute("misName", misName);
        if (userName == null || userName.isEmpty()) {
            return "redirect:/login";
        }
        model.addAttribute("src", src);
        model.addAttribute("username", userName);

        List<Resc> fatherList = new ArrayList<Resc>();
        List<Resc> list = getRescOfUser();
        for (Resc resc: list) {
            if (resc.getFatherId().intValue() == 0){
                fatherList.add(resc);
            }
        }
        model.addAttribute("fatherList", fatherList);

        Map<String, List<Resc>> map = new HashMap<String, List<Resc>>();
        for (Resc father: fatherList) {
            for (Resc resc: list) {
                if (resc.getFatherId().intValue() == father.getId().intValue()){
                    String currentKey = father.getId().toString();
                    if (map.keySet().contains(currentKey)){
                        map.get(currentKey).add(resc);
                    }else{
                        List<Resc> tmp = new ArrayList<Resc>();
                        tmp.add(resc);
                        map.put(currentKey, tmp);
                    }
                }
            }
        }
        model.addAttribute("fatherMap", map);

        User user = getCurrentUser();
        model.addAttribute("user", user);

        ByChannel channel = contentService.findChannel(user.getBizWorkType());
        model.addAttribute("channel", channel);

        return "main";
    }

    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    public void checkCodes(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        Captcha captcha = captchaService.generateCaptcha();
        try {
            WebUtils.setSessionAttribute(request, SESSION_CHECK_CODE, captcha.getCode().toLowerCase());
            response.getOutputStream().write(captcha.getJpegBytes());
        } catch (IOException e) {
            logger.error("check code throw error:" + e);
        }
    }

    @RequestMapping(value = "/checkCodeVerify")
    public void checkCodeVerify(
            @RequestParam("checkCode") String checkCode,
            HttpServletRequest request,
            HttpServletResponse response) {
        String checkCodeReq = (String) WebUtils.getSessionAttribute(request, SESSION_CHECK_CODE);
        if (checkCodeReq == null) {
            returnMsg(response, false);
        } else {
            returnMsg(response, checkCodeReq.equalsIgnoreCase(checkCode.toLowerCase()));
        }
        return;
    }


    /**
     * 用户登录认证
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginController(@ModelAttribute("userForm") UserForm userForm, BindingResult result,
                                  Model model, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectAttributes) throws Exception {
        String checkCode = (String) WebUtils.getSessionAttribute(request, SESSION_CHECK_CODE);

        if(StringUtils.isBlank(userForm.getUsername())) {
            model.addAttribute(Constants.ERROR_KEY, "用户名不能为空");
//            model.addAttribute("misName", misName);
            return "login";
        }

        if(StringUtils.isBlank(userForm.getPassword())) {
            model.addAttribute(Constants.ERROR_KEY, "密码不能为空");
//            model.addAttribute("misName", misName);
            return "login";
        }

        if (userForm != null && userForm.getCheckCode() != null && checkCode != null && !"".equals(checkCode)) {
            String inputCheckCode = userForm.getCheckCode().toLowerCase();
            if (inputCheckCode.length() != 4 || !checkCode.equals(inputCheckCode)) {
                model.addAttribute(Constants.ERROR_KEY, "验证码错误");
//                model.addAttribute("misName", misName);
                return "login";
            }
        } else {
            model.addAttribute(Constants.ERROR_KEY, "验证码错误");
//            model.addAttribute("misName", misName);
            return "login";
        }

        Subject currentUser = SecurityUtils.getSubject();

        String username = userForm.getUsername();
        String password = userForm.getPassword();
        String remoteAddr = getRemoteAddr(request);
        Integer userType = userForm.getUserType();
        ZheUsernamePasswordToken token = new ZheUsernamePasswordToken(username, password, remoteAddr, userType);
        try {
            currentUser.login(token);
            User user = userService.selectByName(getUserName());

            if (user.getStatus().intValue() == BaseState.DELETE.getCode()){
                model.addAttribute(Constants.ERROR_KEY, "用户被锁定,请联系客服!");
                return "login";
            }

            writeLog(request, "用户登陆", null, user.getUsername());
            redirectAttributes.addAttribute("is_login", true);

//            response.sendRedirect(request.getContextPath() + "/index");
            return "redirect:/index";
        } catch (AuthenticationException ae) {
//            ae.printStackTrace();
            model.addAttribute(Constants.ERROR_KEY, "用户名或密码错误");
//            model.addAttribute("username", username);
            writeLog(request, "登陆失败", "试图使用用户名:" + username + "登陆");
            model.addAttribute(Constants.ERROR_KEY, "登录失败，用户名或密码错误!");
            logger.info("登陆失败，用户名或密码错误");
//            model.addAttribute("misName", misName);
            return "login";
        }
    }

    /**
     * json获取菜单数据
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/menulist")
    public void menulistr(Model model) {
        model.addAttribute("list", getRescOfUser());
        return;
    }

    /**
     * 获取用户具有的资源
     *
     * @return
     */
    private List<Resc> getRescOfUser() {
        //获得当前用户
        User currentUser = getCurrentUser();

        //根据当前用户活动当前用户的所有角色
        List<Role> currentRoles = roleService.selectRoleListByUser(currentUser.getId().toString());

        //获取角色具有的所有资源
        List<Resc> rescs = new ArrayList();
        for (Role r : currentRoles) {
            List<Resc> rescList = roleRescService.getRescByRole(r.getId());
            for (Resc resc : rescList) {
                if (resc.getShowUrl().indexOf("?") > -1) {
                    resc.setShowUrl(resc.getShowUrl() + "&rescId=" + resc.getId());
                } else {
                    resc.setShowUrl(resc.getShowUrl() + "?rescId=" + resc.getId());
                }
            }
            rescs.addAll(rescList);
        }

        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        List<Resc> list = new ArrayList<Resc>();
        for (Resc resc : rescs) {
            if (map.get(resc.getId()) == null && resc.getShowMenu() != 0) {
                list.add(resc);
                map.put(resc.getId(), true);
            }
        }

        return list;
    }

    /**
     * 用户没有访问权限所跳转的页面
     *
     * @return
     */
    @RequestMapping(value = "/accessDenied", method = RequestMethod.GET)
    public void accessDenied(Model model) {
        model.addAttribute("message", "无权限");
    }

    @RequestMapping(value = "admin", method = RequestMethod.GET)
    public String admin(Model model) {
        return "admin";
    }

//    @RequestMapping(value = "main", method = RequestMethod.GET)
//    public String main(Model model) {
//        return "main";
//    }

    @RequestMapping(value = "user", method = RequestMethod.GET)
    public String user(Model model) {
        return "user";
    }

    /**
     * 用户登出
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
        //logger.info("用户退出登录");
        String username = getUserName();
        if (username != null) {
            User user = userService.selectByName(getUserName());
            SecurityUtils.getSubject().logout();

            UserForm userForm = new UserForm();
            model.addAttribute("userForm", userForm);
            writeLog(request, "用户注销", null, username);
        }
//        model.addAttribute("misName", misName);
        return "redirect:/login";
    }

    @RequestMapping(value = "/top", method = {RequestMethod.GET, RequestMethod.POST})
    public String top(Model model, HttpServletRequest request, HttpServletResponse response) {
        String username = getUserName();
        model.addAttribute("username", username);
        return "/top";
    }

    /**
     * 用户是否登录
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/islogin", method = RequestMethod.GET)
    public String islogin(Model model) {
        String username = getUserName();
        if (username != null && !username.equals("")) {
            model.addAttribute("flag", true);
        } else {
            model.addAttribute("flag", false);
        }
        return null;
    }

    /**
     * 取出list中重复元素
     *
     * @param list
     * @return
     */
    private List<Resc> removeDuplicate(List<Resc> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).getId() == list.get(i).getId()) {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    /**
     * 用户是否登录
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/refreshPublicPermission", method = RequestMethod.GET)
    public void refreshPublicPermission(Model model) {
        shiroFilter.refreshFilter();
        model.addAttribute("status", "SUCCESS");
        return;
    }

    @RequestMapping(value = "/sendValidMsg", method = RequestMethod.POST)
    public void sendValidMsg(@RequestParam(value = "mobile", required = true) String mobile,
                             HttpServletRequest request, HttpServletResponse response) {

        // 将数据放入到内存
        if (mobile == null) {
            fail("手机号码不能为空！");
        }
        String code = CheckCodeUtil.newCheckCode(mobile);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("code", code);
        map.put("product", ConfigUtil.getSmsFreeSignName());
        boolean flag = CommonUtil.sendMessage(mobile, JSONObject
                .fromObject(map).toString(), ConfigUtil
                .getSmsTemplateCodeRegist());
        if (flag) {
            success("短信发送成功");
        } else {
            fail("短信发送失败");
        }
    }

    @RequestMapping(value = "/submitRegister")
    public String submitRegister(@RequestParam(value = "mobile",required = true) String mobile,
                                 @RequestParam(value = "validate_code",required = true) String validate_code,
                                 @RequestParam(value = "password",required = true) String password,
                                 @RequestParam(value = "re_password",required = true) String re_password,
                                 @RequestParam(value = "invite_by",required = false) String invite_by,
                                 @RequestParam(value = "access_token",required = false) String access_token,
                                 @RequestParam(value = "openid",required = false) String openid,
                                 @RequestParam(value = "unionid",required = false) String unionid,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 Model model,
                                 RedirectAttributes redirectAttributes) {
        try{
            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(validate_code)
                    || StringUtils.isBlank(password) || StringUtils.isBlank(re_password)){
                model.addAttribute(Constants.ERROR_KEY,"参数不正确,请重新输入!");
                return "/register";
            }
            /**
             * 查询该手机的用户是否已经注册了！
             */
            User user = userService.selectByName(mobile);

            /**
             * 手机号码和发送的手机验证码一致性验证
             */
            String result = CheckCodeUtil.verify(mobile, validate_code);
            /**
             * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
             */
            if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {

                /**
                 * 对该手机号码的查询结果进行判断。如果数据库存在
                 */
                if (null != user) {
                    model.addAttribute(Constants.ERROR_KEY,"手机号码已被注册!");
                    return "/register";
                } else {
                    if (password.trim().equals(re_password.trim())){

                        user = new User();
                        user.setUsername(mobile);
                        user.setMobile(mobile);
//                        user.setUserType();
                        user.setPassword(MD5Util.Md5(password.trim()));
                        user.setToken(MD5Util.Md5(user.getPassword()+"boyi"+ DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                        user.setCnName("user-"+RandCharUtil.getRandStr(8));

                        user.setStatus(BaseState.NORMAL.getCode());
                        user.setUserType(UserType.NORMAL_USER.getCode());
                        user.setCreateTime(new DateTime());
                        user.setUpdateTime(new DateTime());
                        user.setOrderCount(0);
                        user.setCoins(50);
                        user.setMoney(new BigDecimal("0.00"));
                        user.setLevelCoins(0);
                        user.setIsHot(0);

                        if (StringUtils.isNotBlank(access_token)){
                            user.setWxAccessToken(access_token);
                        }

                        if (StringUtils.isNotBlank(openid)){
                            user.setWxOpenid(openid);
                        }

                        if (StringUtils.isNotBlank(unionid)){
                            user.setWxUnionid(unionid);
                        }

                        userService.insertUser(user);

                        writeCoinsLog(user, CoinType.REGISTER.getCode(),50);

                        User currentUser = userService.selectByName(mobile);
                        if (currentUser != null) {
                            UserRoleKey userRoleKey = new UserRoleKey();
                            userRoleKey.setRoleId(2);
                            userRoleKey.setUserId(currentUser.getId());
                            roleService.insertUserRoleKey(userRoleKey);

                            if (StringUtils.isNotBlank(invite_by)){
                                User inviteByUser = userService.selectByName(invite_by);
                                if (inviteByUser != null){
                                    ByUserInvite byUserInvite = new ByUserInvite();
                                    byUserInvite.setUserId(currentUser.getId());
                                    byUserInvite.setInviteBy(inviteByUser.getId());
                                    byUserInvite.setStatus(BaseState.DELETE.getCode());
                                    byUserInvite.setCreateTime(new DateTime());
                                    byUserInvite.setUpdateTime(new DateTime());

                                    userService.insertInvite(byUserInvite);
                                }
                            }
                        }


                        Subject subject = SecurityUtils.getSubject();

                        String remoteAddr = getRemoteAddr(request);
                        ZheUsernamePasswordToken token = new ZheUsernamePasswordToken(user.getUsername(), password.trim(), remoteAddr, user.getUserType());
                        subject.login(token);
                        writeLog(request, "用户登陆", null, user.getUsername());
//                        redirectAttributes.addFlashAttribute("is_login", true);
                        response.sendRedirect(request.getContextPath() + "/index?is_login=true");
//                        return "redirect:/index";
                        return null;
                    }else{
                        model.addAttribute(Constants.ERROR_KEY,"重复输入的密码不一致!");
                        return "/register";
                    }
                }
            }else{
                model.addAttribute(Constants.ERROR_KEY,"手机验证码不正确!");
                return "/register";
            }
//            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
//            model.addAttribute("result", false);
        }
        return "/register";
    }

    @RequestMapping(value = "/submitForgetPwd")
    public String submitForgetPwd(@RequestParam(value = "mobile",required = true) String mobile,
                                  @RequestParam(value = "validate_code",required = true) String validate_code,
                                  @RequestParam(value = "password",required = true) String password,
                                  @RequestParam(value = "re_password",required = true) String re_password,
                                  Model model) {
        try{
            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(validate_code)
                    || StringUtils.isBlank(password) || StringUtils.isBlank(re_password)){
                return "/forgetPwd";
            }
            /**
             * 查询该手机的用户是否已经注册了！
             */
            User user = userService.selectByName(mobile);

            /**
             * 手机号码和发送的手机验证码一致性验证
             */
            String result = CheckCodeUtil.verify(mobile, validate_code);

            /**
             * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
             */
            if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {

                /**
                 * 对该手机号码的查询结果进行判断。如果数据库存在
                 */
                if (null != user) {
                    if (password.equalsIgnoreCase(re_password)){
                        user.setPassword(MD5Util.Md5(password.trim()));
                        user.setUpdateTime(new DateTime());

                        userService.updateUser(user);

                        model.addAttribute("result", "修改成功!");
                    }else{
                        return "/forgetPwd";
                    }
                }else{
                    return "/forgetPwd";
                }
            }else{
                return "/forgetPwd";
            }
//            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
//            model.addAttribute("result", false);
        }
        return "/login";
    }

    @RequestMapping(value = "/submitUserBudget")
    public String submitUserBudget(@RequestParam(value = "mobile",required = true) String mobile,
                                @RequestParam(value = "validate_code",required = true) String validate_code,
                                @RequestParam(value = "cname",required = true) String cname,
                                @RequestParam(value = "wed_type",required = true) String wed_type,
                                @RequestParam(value = "money",required = true) String money,
                               HttpServletRequest request,
                               HttpServletResponse response,
                                Model model) {
        try{
            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(validate_code)){
                return "redirect:/index";
            }
            /**
             * 查询该手机的用户是否已经注册了！
             */
            User user = userService.selectByName(mobile);
            /**
             * 手机号码和发送的手机验证码一致性验证
             */
            String result = CheckCodeUtil.verify(mobile, validate_code);

            /**
             * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
             */
            if ("1".equalsIgnoreCase(result)) {
                ByUserWedBudget byUserWedBudget = new ByUserWedBudget();
                byUserWedBudget.setStatus(BaseState.DELETE.getCode());
                if (user != null){
                    byUserWedBudget.setUserId(user.getId());
                }
                byUserWedBudget.setWedType(wed_type);
                byUserWedBudget.setMoney(money);
                byUserWedBudget.setMobile(mobile);
                byUserWedBudget.setContact(cname);

                HttpSession httpSession = request.getSession();

                byUserWedBudget.setCity((String) httpSession.getAttribute("current_city"));
                byUserWedBudget.setCreateTime(new DateTime());
                byUserWedBudget.setUpdateTime(new DateTime());

                userService.insertBudget(byUserWedBudget);
            }
//            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
//            model.addAttribute("result", false);
        }
        return "redirect:/index";
    }

    @RequestMapping(value = "/submitBizRegister")
    public String submitBizRegister(@RequestParam(value = "mobile",required = true) String mobile,
                                 @RequestParam(value = "validate_code",required = true) String validate_code,
                                 @RequestParam(value = "password",required = true) String password,
                                 @RequestParam(value = "re_password",required = true) String re_password,
                                 @RequestParam(value = "invite_by",required = false) String invite_by,
                                 Model model) {

        model.addAttribute("mobile", mobile);
        model.addAttribute("validate_code", validate_code);
        model.addAttribute("password", password);
        model.addAttribute("re_password", re_password);
        model.addAttribute("invite_by", invite_by);

        return "redirect:/biz_register_more";
    }

    @RequestMapping(value = "/biz_register_more")
    public String biz_register_more(@RequestParam(value = "mobile",required = true) String mobile,
                                    @RequestParam(value = "validate_code",required = true) String validate_code,
                                    @RequestParam(value = "password",required = true) String password,
                                    @RequestParam(value = "re_password",required = true) String re_password,
                                    @RequestParam(value = "invite_by",required = false) String invite_by,
                                    Model model) {
//        UserForm userForm = new UserForm();
//        model.addAttribute("userForm", userForm);
////        model.addAttribute("misName", misName);
//
//        User user = getCurrentUser();
//
//        if (user == null || user.getBizWorkType() != null){
//            return "/accessDenied";
//        }

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(validate_code)
                || StringUtils.isBlank(password) || StringUtils.isBlank(re_password)){
            model.addAttribute(Constants.ERROR_KEY,"参数不正确,请重新输入!");
            return "/biz_register";
        }

        /**
         * 查询该手机的用户是否已经注册了！
         */
        User user = userService.selectByName(mobile);

        /**
         * 手机号码和发送的手机验证码一致性验证
         */
        String result = CheckCodeUtil.verify(mobile, validate_code);
        /**
         * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
         */
        if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {

            /**
             * 对该手机号码的查询结果进行判断。如果数据库存在
             */
            if (null != user) {
                model.addAttribute(Constants.ERROR_KEY, "手机号码已被注册!");
                return "/biz_register";
            } else {
                if (!password.trim().equals(re_password.trim())){
                    model.addAttribute(Constants.ERROR_KEY,"重复输入的密码不一致!");
                    return "/biz_register";
                }
            }
        }else{
            model.addAttribute(Constants.ERROR_KEY,"手机验证码不正确!");
            return "/biz_register";
        }

        List<ByChannel> channels = contentService.selectAllSubChannelList();

        model.addAttribute("workTypeList", channels);
        model.addAttribute("mobile", mobile);
        model.addAttribute("validate_code", validate_code);
        model.addAttribute("password", password);
        model.addAttribute("re_password", re_password);
        model.addAttribute("invite_by", invite_by);

        return "/biz_register_more";
    }

    @RequestMapping(value = "/submitBizRegisterDetail")
    public String submitBizRegisterDetail(@RequestParam(value = "mobile",required = true) String mobile,
                                          @RequestParam(value = "validate_code",required = true) String validate_code,
                                          @RequestParam(value = "password",required = true) String password,
                                          @RequestParam(value = "re_password",required = true) String re_password,
                                          @RequestParam(value = "invite_by",required = false) String invite_by,
                                        @RequestParam(value = "avatar", required = false) MultipartFile avatar,
                                        @RequestParam(value = "file", required = false) MultipartFile file,
                                        @RequestParam(value = "cn_name",required = false) String cn_name,
                                        @RequestParam(value = "user_type",required = false) Integer user_type,
                                        @RequestParam(value = "biz_work_type",required = false) Integer biz_work_type,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                        Model model,
                                        RedirectAttributes redirectAttributes) {

        try{
            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(validate_code)
                    || StringUtils.isBlank(password) || StringUtils.isBlank(re_password)){
                model.addAttribute("result", "参数不正确,请重新输入!");
                return "/biz_register";
            }
            /**
             * 查询该手机的用户是否已经注册了！
             */
//            User user = userService.selectByName(mobile);
            User user = null;
            /**
             * 手机号码和发送的手机验证码一致性验证
             */
//            String result = CheckCodeUtil.verify(mobile, validate_code);
            /**
             * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
             */
//            if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {
//
                /**
                 * 对该手机号码的查询结果进行判断。如果数据库存在
                 */
//                if (null != user) {
//                    model.addAttribute(Constants.ERROR_KEY,"手机号码已被注册!");
//                    return "/biz_register";
//                } else {
                    if (password.trim().equals(re_password.trim())){
                        user = new User();
                        user.setUsername(mobile);
                        user.setMobile(mobile);
//                        user.setUserType();
                        user.setPassword(MD5Util.Md5(password.trim()));
                        user.setToken(MD5Util.Md5(user.getPassword()+"boyi"+ DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                        user.setCnName("user-"+RandCharUtil.getRandStr(8));

                        user.setStatus(BaseState.NORMAL.getCode());
                        user.setUserType(UserType.NORMAL_USER.getCode());
                        user.setCreateTime(new DateTime());
                        user.setUpdateTime(new DateTime());
                        user.setOrderCount(0);
                        user.setCoins(50);
                        user.setMoney(new BigDecimal("0.00"));
                        user.setLevelCoins(0);
                        user.setIsHot(0);

                        user.setCnName(cn_name);
                        user.setUserType(user_type);
                        user.setBizWorkType(biz_work_type);

                        if (avatar != null && avatar.getSize() > 0){
                            String avatar_img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

                            UploadUtil.uploadData(avatar.getBytes(), avatar_img_url);

                            user.setAvatar(avatar_img_url);
                        }


                        userService.insertUser(user);

                        writeCoinsLog(user, CoinType.REGISTER.getCode(),50);

                        User currentUser = userService.selectByName(mobile);
                        if (currentUser != null) {
                            UserRoleKey userRoleKey = new UserRoleKey();
                            userRoleKey.setRoleId(2);
                            userRoleKey.setUserId(currentUser.getId());
                            roleService.insertUserRoleKey(userRoleKey);

                            if (StringUtils.isNotBlank(invite_by)){
                                User inviteByUser = userService.selectByName(invite_by);
                                if (inviteByUser != null){
                                    ByUserInvite byUserInvite = new ByUserInvite();
                                    byUserInvite.setUserId(currentUser.getId());
                                    byUserInvite.setInviteBy(inviteByUser.getId());
                                    byUserInvite.setStatus(BaseState.DELETE.getCode());
                                    byUserInvite.setCreateTime(new DateTime());
                                    byUserInvite.setUpdateTime(new DateTime());

                                    userService.insertInvite(byUserInvite);
                                }
                            }
                        }


                        //认证资料

                        //新增认证信息
                        ByUserBizAuth byUserBizAuth = new ByUserBizAuth();
                        byUserBizAuth.setUserId(user.getId());
                        byUserBizAuth.setName("认证材料");
                        byUserBizAuth.setDescn("认证材料");
                        byUserBizAuth.setStatus(BaseState.DELETE.getCode());
                        byUserBizAuth.setAuthType(AuthType.BIZ_AUTH.getCode());
                        byUserBizAuth.setCreateTime(new DateTime());
                        byUserBizAuth.setUpdateTime(new DateTime());

                        if (file != null && file.getSize() > 0){
                            String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

                            UploadUtil.uploadData(file.getBytes(), img_url);
                            byUserBizAuth.setImgUrl(img_url);
                        }

                        userService.insertBizVerify(byUserBizAuth);

                        //验证跳转
                        Subject subject = SecurityUtils.getSubject();

                        String remoteAddr = getRemoteAddr(request);
                        ZheUsernamePasswordToken token = new ZheUsernamePasswordToken(user.getUsername(), password.trim(), remoteAddr, user.getUserType());
                        subject.login(token);
                        writeLog(request, "用户登陆", null, user.getUsername());
//                        redirectAttributes.addFlashAttribute("is_login", true);
                        response.sendRedirect(request.getContextPath() + "/index?is_login=true");
                        return null;
                    }else{
                        model.addAttribute(Constants.ERROR_KEY,"重复输入的密码不一致!");
                        return "/biz_register";
                    }
//                }
//            }else{
//                model.addAttribute(Constants.ERROR_KEY,"手机验证码不正确!");
//                return "/biz_register";
//            }
//            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
//            model.addAttribute("result", false);
        }
        return "/biz_register";
    }

    @RequestMapping(value = "/wxlogin")
    public String wxlogin(@RequestParam(value = "code",required = false) String code,
                          @RequestParam(value = "state",required = false) String state,
                          HttpServletRequest request,
                          HttpServletResponse response,
                          RedirectAttributes redirectAttributes,
                          Model model) {
        if (StringUtils.isBlank(code)){
            return "/login";
        }

        String appid = "wx2d65111563f0c621";
        String secret = "2d856e5c36df4bbf452d5984a81a64a9";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        com.alibaba.fastjson.JSONObject responseStr = HttpGetOrPost.sendGet(url);

        try{
            if (!responseStr.containsKey("errcode")) {

                model.addAttribute("access_token", responseStr.getString("access_token"));
                model.addAttribute("openid", responseStr.getString("openid"));
                model.addAttribute("unionid", responseStr.getString("unionid"));

                String unionid = responseStr.getString("unionid");
                if (StringUtils.isNotBlank(unionid)) {
                    User user = userService.selectUserByWxId(null, unionid);

                    if (user != null){
                        if (user.getStatus().intValue() == BaseState.DELETE.getCode()){
                            model.addAttribute(Constants.ERROR_KEY, "用户被锁定,请联系客服!");
                            return "/login";
                        }

                        //验证跳转
                        Subject subject = SecurityUtils.getSubject();

                        String remoteAddr = getRemoteAddr(request);
                        ZheUsernamePasswordToken token = new ZheUsernamePasswordToken(user.getUsername(), responseStr.getString("unionid"), remoteAddr, LoginType.WEIXIN.getCode());
                        subject.login(token);
                        writeLog(request, "用户登陆", null, user.getUsername());

                        response.sendRedirect(request.getContextPath() + "/index?is_login=true");
                        return null;
    //                    return "redirect:/index";

                    }
                }

            }
        }catch (Exception ex){
            //do thing
        }
        return "/wxlogin";
   }


    @RequestMapping(value = "/simpleFileUpload")
    public void simpleFileUpload(HttpServletRequest request,
                               HttpServletResponse response,
                               Model model) {

        try {
            request.setCharacterEncoding( "utf-8" );

            response.setHeader("Content-Type" , "text/html");

            String rootPath = request.getRealPath( "/common/ueditor/jsp/controller.jsp" );
            //自定义保存的根目录，从而达到上传目录不在是项目下，默认为项目根目录
//            String saveRootPath = rootPath;
            //saveRootPath = "D:/";
//            saveRootPath = PropertiesConfig.getProperty("img_upload_path", "/home");;
//            System.out.println(saveRootPath);
            response.getWriter().write( new ActionEnter( request,rootPath ).exec() );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //alipay
    /**
     * 商家子订单退款异步通知接口
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/alipay_notify_url")
    public void alipay_notify_url(HttpServletRequest request, HttpServletResponse response) throws IOException{
        logger.debug("支付宝支付服务器异步通知请求    orderNum="+request.getParameter("out_trade_no"));
        String orderNum = request.getParameter("out_trade_no");
        String trade_status = request.getParameter("trade_status");

        PrintWriter out = response.getWriter();

        //获取支付宝POST过来反馈信息
        Map<String,String> params= AlipayParams.getAlipayParamsForMap(request);

//        String trade_status=orders.getAlipaytradestatus();

        if(Constants.IS_DEBUG || (params.size()>=1 && AlipayNotify.verify(params) && params.get("notify_type")!=null && params.get("notify_type").trim().equals("trade_status_sync") )){
            /**
             * a、在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS或TRADE_FINISHED  时，支付宝才会认定为买家付款成功
             * b、交易状态 TRADE_SUCCESS 的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功；
             * c、交易状态 TRADE_FINISHED 的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；或者，商户签约的产品支持退款功能的前提下，交易已经成功并且已经超过可退款期限；
             */
            if( trade_status!=null && (trade_status.trim().equals("TRADE_FINISHED") || trade_status.trim().equals("TRADE_SUCCESS"))){
                logger.debug("支付宝(支付完成;买家付款成功)异步通知: success");

                if (!CitiesUtil.isNumeric(orderNum) && orderNum.indexOf("bt-") != -1 && orderNum.substring(0,3).equalsIgnoreCase("bt-")){
                    //批量支付
                    ByUserBatchPayOrder batchPayOrder = userOrderService.findByUserBatchPayOrderByNum(orderNum);

                    String orderIds[] = batchPayOrder.getOrderIds().split(",");

                    if (orderIds != null && orderIds.length > 0) {
                        List<Integer> orderIdList = new ArrayList<Integer>();
                        List<Integer> bizUserIdList = new ArrayList<Integer>();
                        for (int i = 0; i < orderIds.length; i++) {
                            orderIdList.add(Integer.valueOf(orderIds[i]));
                        }
                        List<ByUserOrder> orderList = userOrderService.findByUserOrderList(orderIdList);

                        for (ByUserOrder current : orderList) {
                            current.setPayType(Const.OrdersPayMethod.ALIPAY);
                            current.setPayStatus(batchPayOrder.getPriceType());
//                            orders.setNeedPayPrice(oldOrder.getPrice().subtract(orders.getAlipaytotalfee()));
                            userOrderService.insertByUserOrder(current);

                            bizUserIdList.add(current.getBizUserId());
                        }

                        List<User> bizUserList = new ArrayList<User>();
                        if (bizUserIdList != null && bizUserIdList.size() > 0){
                            bizUserList = userService.selectUserByIds(bizUserIdList);
                            for(User biz : bizUserList){
                                //send msg
                                Map<String, Object> map = new LinkedHashMap<String, Object>();
                                map.put("code", ""+biz.getId());

                                if (biz != null && StringUtils.isNotBlank(biz.getMobile()) && biz.getBizWorkType() != null) {
                                    CommonUtil.sendMessage(biz.getMobile(), JSONObject
                                            .fromObject(map).toString(), ConfigUtil
                                            .getSms_template_code_new_order());
                                }
                            }
                        }

                    }
                }else{
                    ByUserOrder byUserOrder = userOrderService.findByUserOrder(Integer.valueOf(orderNum));

                    //单个支付
                    byUserOrder =AlipayParams.getAlipayParamsForOrder(byUserOrder, params);
                    byUserOrder.setPayType(Const.OrdersPayMethod.ALIPAY);



                    byUserOrder.setNeedPayPrice(byUserOrder.getPrice().subtract(byUserOrder.getAlipaytotalfee()));
                    if (byUserOrder.getPrice().compareTo(byUserOrder.getAlipaytotalfee()) == 0){
                        byUserOrder.setPayStatus(OrderPayStatus.PAY_ALL.getCode());
                    }else {
                        byUserOrder.setPayStatus(OrderPayStatus.PAY_DEPOSIT.getCode());
                    }

                    userOrderService.insertByUserOrder(byUserOrder);

                    //send msg
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("code", ""+byUserOrder.getStatus());

                    User bizUser = userService.selectUserById(byUserOrder.getBizUserId());
                    if (bizUser != null && StringUtils.isNotBlank(bizUser.getMobile()) && bizUser.getBizWorkType() != null){
                        if (bizUser != null && StringUtils.isNotBlank(bizUser.getMobile())) {
                            CommonUtil.sendMessage(bizUser.getMobile(), JSONObject
                                    .fromObject(map).toString(), ConfigUtil
                                    .getSms_template_code_new_order());
                        }
                    }

                }

//				out.println("success".toString().trim());	//请不要修改或删除
                out.print("success".toString().trim());	//请不要修改或删除
            }else{
                logger.debug("支付(卖买家付款还未完成)宝异步通知: trade_status="+trade_status);
                out.print("fail".toString().trim());
            }
        }else{
            logger.debug("支付宝异步通知校验不合法: fail--数字校验未通过");
            out.print("fail".toString().trim());
        }
    }

    /**
     * 商家子订单退款同步通知接口
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/alipay_return_url")
    public void alipay_return_url(HttpServletRequest request, HttpServletResponse response) throws IOException{
        logger.debug("支付宝支付服务器同步通知请求    orderNum="+request.getParameter("out_trade_no"));
        String orderNum = request.getParameter("out_trade_no");
        String trade_status = request.getParameter("trade_status");

        PrintWriter out = response.getWriter();

        //获取支付宝POST过来反馈信息
        Map<String,String> params= AlipayParams.getAlipayParamsForMap(request);

//        String trade_status=orders.getAlipaytradestatus();

        if(Constants.IS_DEBUG || (params.size()>=1 && AlipayNotify.verify(params) && params.get("notify_type")!=null && params.get("notify_type").trim().equals("trade_status_sync") )){
            /**
             * a、在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS或TRADE_FINISHED  时，支付宝才会认定为买家付款成功
             * b、交易状态 TRADE_SUCCESS 的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功；
             * c、交易状态 TRADE_FINISHED 的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；或者，商户签约的产品支持退款功能的前提下，交易已经成功并且已经超过可退款期限；
             */
            if( trade_status!=null && (trade_status.trim().equals("TRADE_FINISHED") || trade_status.trim().equals("TRADE_SUCCESS"))){
                logger.debug("支付宝(支付完成;买家付款成功)同步通知: success");

                if (!CitiesUtil.isNumeric(orderNum) && orderNum.indexOf("bt-") != -1 && orderNum.substring(0,3).equalsIgnoreCase("bt-")){
                    //批量支付
                    ByUserBatchPayOrder batchPayOrder = userOrderService.findByUserBatchPayOrderByNum(orderNum);

                    String orderIds[] = batchPayOrder.getOrderIds().split(",");

                    if (orderIds != null && orderIds.length > 0) {
                        List<Integer> orderIdList = new ArrayList<Integer>();
                        List<Integer> bizUserIdList = new ArrayList<Integer>();
                        for (int i = 0; i < orderIds.length; i++) {
                            orderIdList.add(Integer.valueOf(orderIds[i]));
                        }
                        List<ByUserOrder> orderList = userOrderService.findByUserOrderList(orderIdList);
                        Integer userId = null;
                        for (ByUserOrder current : orderList) {
                            current.setPayType(Const.OrdersPayMethod.ALIPAY);
                            current.setPayStatus(batchPayOrder.getPriceType());
//                            orders.setNeedPayPrice(oldOrder.getPrice().subtract(orders.getAlipaytotalfee()));

                            userOrderService.insertByUserOrder(current);
                            userId = current.getUserId();
                            bizUserIdList.add(current.getBizUserId());
                            ByMoneyLog byMoneyLog = new ByMoneyLog();
                            byMoneyLog.setUserId(current.getBizUserId());
                            byMoneyLog.setMoneyType(1);
                            if (batchPayOrder.getPriceType().intValue() == OrderPayStatus.PAY_ALL.getCode()){
                                byMoneyLog.setAmount(current.getPrice());
                            }else{
                                byMoneyLog.setAmount(current.getDeposit());
                            }
                            byMoneyLog.setCreateTime(new DateTime());
                            userService.insertSelectiveByMoneyLog(byMoneyLog);
                        }
                        User payUser = userService.selectUserById(userId);
                        List<User> bizUserList = new ArrayList<User>();
                        if (bizUserIdList != null && bizUserIdList.size() > 0){
                            bizUserList = userService.selectUserByIds(bizUserIdList);
                            for(User biz : bizUserList){
                                //send msg
                                Map<String, Object> map = new LinkedHashMap<String, Object>();
                                map.put("code", ""+biz.getId());


                                if (biz != null && StringUtils.isNotBlank(biz.getMobile()) && biz.getBizWorkType() != null) {
                                    CommonUtil.sendMessage(biz.getMobile(), JSONObject
                                            .fromObject(map).toString(), ConfigUtil
                                            .getSms_template_code_new_order());
                                    String content = (payUser != null ? payUser.getCnName() : "") + "已付款，请及时接单";
                                    ByUserMessage userMessage = new ByUserMessage();
                                    userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                                    userMessage.setContent(content);
                                    userMessage.setUserId(biz.getId());
                                    userService.insertUserMessage(userMessage);
                                }
                            }
                        }
                    }
                }else{
                    ByUserOrder byUserOrder = userOrderService.findByUserOrder(Integer.valueOf(orderNum));

                    //单个支付
                    byUserOrder =AlipayParams.getAlipayParamsForOrder(byUserOrder, params);
                    byUserOrder.setPayType(Const.OrdersPayMethod.ALIPAY);
                    ByMoneyLog byMoneyLog = new ByMoneyLog();
                    byMoneyLog.setUserId(byUserOrder.getBizUserId());
                    byMoneyLog.setMoneyType(1);
                    byMoneyLog.setCreateTime(new DateTime());

                    byUserOrder.setNeedPayPrice(byUserOrder.getPrice().subtract(byUserOrder.getAlipaytotalfee()));
                    if (byUserOrder.getPrice().compareTo(byUserOrder.getAlipaytotalfee()) == 0){
                        byUserOrder.setPayStatus(OrderPayStatus.PAY_ALL.getCode());
                        byMoneyLog.setAmount(byUserOrder.getPrice());
                    }else {
                        byUserOrder.setPayStatus(OrderPayStatus.PAY_DEPOSIT.getCode());
                        byMoneyLog.setAmount(byUserOrder.getDeposit());
                    }
                    userService.insertSelectiveByMoneyLog(byMoneyLog);
                    userOrderService.insertByUserOrder(byUserOrder);
                    User payUser = userService.selectUserById(byUserOrder.getUserId());
                    //send msg
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("code", ""+byUserOrder.getStatus());

                    User bizUser = userService.selectUserById(byUserOrder.getBizUserId());
                    if (bizUser != null && StringUtils.isNotBlank(bizUser.getMobile()) && bizUser.getBizWorkType() != null){
                        CommonUtil.sendMessage(bizUser.getMobile(), JSONObject
                                .fromObject(map).toString(), ConfigUtil
                                .getSms_template_code_new_order());
                        String content = (payUser != null ? payUser.getCnName() : "") + "已付款，请及时接单";
                        ByUserMessage userMessage = new ByUserMessage();
                        userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                        userMessage.setContent(content);
                        userMessage.setUserId(bizUser.getId());
                        userService.insertUserMessage(userMessage);
                    }
                }

//				out.println("success".toString().trim());	//请不要修改或删除
//                out.print("success".toString().trim());	//请不要修改或删除
                out.print("支付宝付款成功!");
                response.sendRedirect("/");
            }else{
                logger.debug("支付(卖买家付款还未完成)宝同步通知: trade_status="+trade_status);
//                out.print("fail".toString().trim());
                out.print("支付宝付款失败!");
            }
        }else{
            logger.debug("支付宝同步通知校验不合法: fail--数字校验未通过");
//            out.print("fail".toString().trim());
            out.print("支付宝付款失败!");
        }
    }

    /**
     * 商家子订单退款异步通知接口
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/orderBusinessRefund")
    public void orderBusinessRefund(HttpServletRequest request, HttpServletResponse response) throws IOException{

//        LOG.debug("doRequest(interface/orderBusinessRefund)--支付宝支付服务器(退款)异步通知请求");
//        PrintWriter out = response.getWriter();
//
//        //获取支付宝POST过来反馈信息
//        Map<String,String>  params=AlipayParams.getAlipayParamsForMap(request);
//        OrdersBusiness  ordersBusiness =AlipayParams.getAlipayParamsForOrdersBusiness(params);
//        String trade_status=params.get("trade_status");
//
//
//        if(Env.unitTest || (params.size()>=1 && AlipayNotify.verify(params))){
//            if(params.get("notify_type")!=null && params.get("notify_type").trim().equals("trade_status_sync")){
//                if(trade_status!=null && (trade_status.trim().equals("TRADE_CLOSED"))){
//                    //交易关闭处理，即用户已完成了全部退款
//                    LOG.debug("支付宝(交易关闭处理，即用户已完成了全部退款)异步通知: success");
//                }else{
//                    LOG.debug("支付宝(交易未关闭，执行了部分退款操作)异步通知: success");
//                }
//                out.print("success");	//请不要修改或删除
//                return;
//            }else if(params.get("notify_type")!=null && params.get("notify_type").trim().equals("batch_refund_notify")){
//                String  result_details=params.get("result_details");
//                if(result_details==null){
//                    LOG.debug("支付宝退款返回的退款详细信息错误： result_details=" +result_details);
//                    out.print("fail");
//                    return;
//                }
//                String[] result_detailsArray=result_details.split("^");
//                if(result_detailsArray.length<=3 || !result_detailsArray[2].trim().equals("SUCCESS")){
//                    LOG.debug("支付宝退款返回的退款详细信息错误： result_details=" +result_details);
//                    out.print("fail");
//                    return;
//                }
//
//                if(result_detailsArray[2].trim().equals("SUCCESS")){
//
//                    //退款成功后业务操作
//                    ordersService.doOrdersBusinessRefund(ordersBusiness);
//                    LOG.debug("支付宝(该笔退款成功)退款异步通知： success");
//                    out.print("success");	//请不要修改或删除
//                    return;
//                }
//
//
//            }else{
//                LOG.debug("支付宝(退款)异步通知校验不合法: fail---notify_type="+params.get("notify_type"));
//                out.print("fail");
//                return;
//            }
//
//        }else{
//            LOG.debug("支付宝(退款)异步通知校验不合法: fail---数字验签未通过");
//            out.print("fail");
//            return;
//        }

    }
}
